# coding=utf-8
"""
@author : leecrest
@time   : 2014/7/21 11:18
@brief  : 数据缓存，对redis的包装
"""
import wafer


if not "g_CacheDict" in globals():
	g_CacheDict = {}
	g_SyncTime = 3000
	g_TimerID = 0


class CCache(object):
	def __init__(self, sTable, sKey):
		self.m_Table = sTable
		self.m_Key = sKey
		self.m_Update = False

	def Update(self):
		self.m_Update = True


	def Load(self):
		data = wafer.GetRedis().hget(self.m_Table, self.m_Key)
		self.OnLoad(data)


	def Save(self):
		if not self.m_Update:
			return False
		data = self.OnSave()
		wafer.GetRedis().hset(self.m_Table, self.m_Key, data)
		self.m_Update = False
		return True


def CheckTimer():
	global g_TimerID, g_SyncTime, g_CacheDict
	if g_CacheDict:
		if g_TimerID > 0:
			return
		g_TimerID = wafer.SetTimer(0, "CacheSync", CacheSync, 0, g_SyncTime)
	elif g_TimerID > 0:
		wafer.RemoveTimer(g_TimerID)
		g_TimerID = 0


def CacheSync():
	global g_CacheDict
	ValidList = []
	for k, cache in g_CacheDict.iteritems():
		if not cache.Save():
			ValidList.append(k)
	for k in ValidList:
		del g_CacheDict[k]
	if not g_CacheDict:
		CheckTimer()


#设置同步时间
def SetSyncTime(iTime):
	global g_SyncTime, g_TimerID
	if not iTime or iTime == g_SyncTime:
		return
	g_SyncTime = iTime
	if g_TimerID > 0:
		g_TimerID = wafer.SetTimer(g_TimerID, "CacheSync", CacheSync, 0, g_SyncTime)


#注册同步
def RegCache(sTable, sKey, obj):
	global g_CacheDict
	k = (sTable, str(sKey))
	if k in g_CacheDict:
		wafer.log.Error("(%s, %s)重复注册了", sTable, sKey)
		return False
	g_CacheDict[k] = obj
	obj.Load()
	CheckTimer()
	return True


#注销同步
def UnRegCache(sTable, sKey):
	global g_CacheDict
	k = (sTable, str(sKey))
	cache = g_CacheDict.get(k, None)
	if not cache:
		return
	del g_CacheDict[k]
	cache.Save()
	CheckTimer()


__all__ = ["SetSyncTime", "RegCache", "UnRegCache", "CCache"]



